{% extends 'base.html' %}
{% block content %}
  <button id="downloadBtn" class="btn btn-primary btn-lg">
    <i class="bi bi-download me-2"></i>导出 CSV
  </button>

  <script>
    document.getElementById('downloadBtn').addEventListener('click', async function() {
      const btn = this;
      const originalHtml = btn.innerHTML;
      
      try {
        // 显示加载状态
        btn.disabled = true;
        btn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>导出中...';
        
        // 发起导出请求
        const response = await fetch('/export/csv');
        if (!response.ok) {
          throw new Error(`导出失败: ${response.statusText}`);
        }
        
        // 处理导出文件
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'exported_data.csv';
        document.body.appendChild(a);
        a.click();
        
        // 清理
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
        
        // 显示成功状态
        btn.innerHTML = '<i class="bi bi-check-circle me-2"></i>导出成功!';
        btn.classList.remove('btn-primary');
        btn.classList.add('btn-success');
        
        // 恢复原始状态
        setTimeout(() => {
          btn.innerHTML = originalHtml;
          btn.classList.remove('btn-success');
          btn.classList.add('btn-primary');
          btn.disabled = false;
        }, 2000);
        
      } catch (error) {
        // 显示错误状态
        btn.innerHTML = '<i class="bi bi-exclamation-circle me-2"></i>导出失败';
        btn.classList.remove('btn-primary');
        btn.classList.add('btn-danger');
        
        // 恢复原始状态
        setTimeout(() => {
          btn.innerHTML = originalHtml;
          btn.classList.remove('btn-danger');
          btn.classList.add('btn-primary');
          btn.disabled = false;
        }, 3000);
        
        alert(`导出失败: ${error.message}`);
      }
    });
  </script>
{% endblock %}    